#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <string>

#include "image_tools/image_tools.hpp"

int main(int argc, char* argv[])
{
    /* 参数校验与配置 */
    if (argc != 4) {
        printf("> FMT: ./demo_run <filename> <width> <height>\n");
        printf("> DEM: ./demo_run img.rgb 1920 1080\n");
        exit(EXIT_FAILURE);
    }

    int img_w = atoi(argv[2]);
    int img_h = atoi(argv[3]);
    int rgb_img_size = img_w * img_h * 3;
    int raw_img_size = img_w * img_h * 2;
    FILE* rgb_img_fp = fopen(argv[1], "rb");
    FILE* raw_img_fp = fopen((std::string(argv[1])+".out").c_str(), "wb");

    if (img_w <= 0 || img_h <= 0 || rgb_img_fp == nullptr || raw_img_fp == nullptr) {
        printf("para error, img_w:%d img_h:%d rgb_img_fp:%p raw_img_fp:%p.\n", img_w, img_h, rgb_img_fp, raw_img_fp);
        exit(EXIT_FAILURE);
    }

    std::vector<uint8_t> rgb_buff(rgb_img_size);
    std::vector<uint16_t> raw_buff(raw_img_size);
    int ret = fread(rgb_buff.data(), 1, rgb_img_size, rgb_img_fp);
    if (ret != rgb_img_size) {
        printf("fread rgb_img_fp failed, ret:%d %s.\n", ret, strerror(errno));
        exit(EXIT_FAILURE);
    }

    /* 转换 */
    ImageTools::rgb888_to_bayer_rggb16(rgb_buff.data(), raw_buff.data(), img_h, img_w);
    ret = fwrite(raw_buff.data(), 1, raw_img_size, raw_img_fp);
    printf("> convert success, output filename: %s, file length: %d.\n", (std::string(argv[1])+".out").c_str(), ret);

    fclose(rgb_img_fp);
    fclose(raw_img_fp);
    return 0;
}